/* **********************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This source code is subject to terms and conditions of the Shared Source License
* for DSL Editor PowerToy. A copy of the license can be found in the License.htm file
* at the root of this distribution. If you can not locate the Shared Source License
* for DSL Editor PowerToy, please obtain a copy from: http://www.codeplex.com/dsltreegrideditor/Project/License.aspx.
* By using this source code in any fashion, you are agreeing to be bound by
* the terms of the Shared Source License for DSL Editor PowerToy.
*
* You must not remove this notice, or any other, from this software.
*
* **********************************************************************************/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

using Microsoft.VisualStudio.Modeling;
using Microsoft.VisualStudio.Modeling.Diagrams;

namespace DslEditorPowerToy.Languages.EditorConfiguration
{
    /// <summary>
    /// Helper class for shapes
    /// </summary>
    internal static class ShapeHelper
    {
        /// <summary>
        /// Forces a property value changed handler to fire.
        /// Used as a workaround to fix bug in DSLtools that is preventing property change handlers 
        /// fromm firing very first time diagram is openend
        /// </summary>
        public static void ForceAssociatedPropertyValueUpdate(NodeShape shape, string propertyName)
        {
            ModelElement element = shape.Subject;
            if (element == null)
                throw new ArgumentNullException("element");

            if (!element.Store.InUndoRedoOrRollback)
            {
                DomainPropertyInfo propertyInfo = element.GetDomainClass().FindDomainProperty(propertyName, true);
                if (null != propertyInfo)
                {
                    using (Transaction transaction = element.Store.TransactionManager.BeginTransaction(Resources.Transaction_ForcePropertyUpdate))
                    {
                        // Reflective call to handler.InternalNotifyValueChange(element, oldValue, newValue);
                        // Call has to be reflective as the actual method is generic.
                        MethodInfo method = propertyInfo.ValueHandler.GetType().GetMethod("InternalNotifyValueChange", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance);
                        method.Invoke(propertyInfo.ValueHandler, new object[] { element, propertyInfo.GetValue(element), propertyInfo.GetValue(element) });

                        transaction.Commit();
                    }
                }
            }
        }

    }
}
